#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2011
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author: Jesus Carrero <j.o.carrero@gmail.com>
# Mountain View, CA
#

from utils.Quadrature import LegendreGaussQuadrature
from GBMSolverAdaptor import GBMSolverAdaptor


class NumericalOptionGBM(GBMSolverAdaptor):
    """ main class to price derivaties under geometric brownian motion. """

    __slots__ = ['m_opt_type', 'm_contract_type', 'm_greeks',
                 'm_shape_func', 'm_price_mode']

    def __init__(self, opt_type, time2_mat, prices, strikes,
            ntime_steps, nsegs, smin=None, smax=None):
        """ instantiate object of class NumericalOptionGBM."""
        if opt_type not in ['A', 'E']:
            raise Warning('available pricing types: [American, European]')

        self.m_price_mode = 'price-range'
        (self.m_greeks, self.m_shape_func) = (None, None)
        (self.m_opt_type, self.m_contract_type) = (opt_type, 'vanilla')

        GBMSolverAdaptor.__init__(self, time2_mat, prices, strikes,
                ntime_steps, nsegs, smin, smax)

    def set_price_mode(self, price_mode):
        """ set price mode."""
        if price_mode not in ['greeks', 'price-range', 'price']:
            raise Warning('pricing modes: [greeks, price, price-range]')
        self.m_price_mode = price_mode


    def set_contract_type(self, contract_type):
        """ set contract type."""
        assert contract_type in ['vanilla', 'digital']
        self.m_contract_type = contract_type

    def _price_contract(self):
        """ price derivative. """
        assert self.m_shape_func is not None
        quads = LegendreGaussQuadrature(5)
        self.set_sfunc_and_quads(self.m_shape_func, quads)

        self.set_up_problem()
        if 'A' == self.m_opt_type:
            self.set_constraint(self.get_pival())

        solution = self.solve()
        self.m_greeks = self._post_process(solution)

        self.m_greeks[:, 3] = (self.m_greeks[:, 3] - self.m_greeks[:,
                               2]) / self.m_greeks[:, 0] ** 2
        self.m_greeks[:, 2] = self.m_greeks[:, 2] / self.m_greeks[:, 0]

        if 'greeks' == self.m_price_mode:
            return (self.m_greeks[:, 0], self.m_greeks[:, 1:])
        elif 'price-range' == self.m_price_mode:
            return (self.m_greeks[:, 0], self.m_greeks[:, 1])
        else:
            stpv = self.get_stock_pres_val()
            (grid, price) = (self.m_greeks[:, 0], self.m_greeks[:, 1])
            return (price[grid < stpv][-1] + price[stpv <= grid][0]) / 2.

    def get_greeks(self):
        """ get greeks."""
        assert self.m_greeks is not None
        return self.m_greeks

    def set_shape_functions(self, shape_func):
        """ set shape functions. """
        self.m_shape_func = shape_func

    def price_call(self):
        """  price call contract. """
        self.set_lbc(self._zero)
        if 'vanilla' == self.m_contract_type:
            self.set_ivalf(self._call_va_present_val)
            self.set_rbc(self._ca_vanilla_rbc)
        elif 'digital' == self.m_contract_type:
            self.set_ivalf(self._call_di_present_val)
            self.set_rbc(self._digital_bc)
        else:
            assert False
        return self._price_contract()

    def price_put(self):
        """ price put contract."""
        self.set_rbc(self._zero)
        if 'vanilla' == self.m_contract_type:
            self.set_ivalf(self._put_va_present_val)
            self.set_lbc(self._put_va_lbc)
        elif 'digital' == self.m_contract_type:
            self.set_ivalf(self._put_di_present_val)
            self.set_rbc(self._digital_bc)
        else:
            assert False

        return self._price_contract()


